package com.geek.log4jcontrol.core;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import com.geek.log4jcontrol.commons.ConfigConstants;
import com.geek.util.FileContextUtil;

public class LogTaker {
	private long logFileSize = 0;

	public String getLogStrByFileSize(String logfilePath, long fileSize) throws IOException  {
		
		StringBuffer logStr = new StringBuffer();
		String root = ConfigConstants.LOG_ROOT;
		if (root.endsWith("/")) {
			root = root.substring(0, root.length() - 1);
		}
		File logFile = new File(root + File.separator + logfilePath);
		RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
		try {
			logFileSize = randomFile.length();
			long monitorSize = fileSize * 1024l;
			long startSize = logFileSize - monitorSize;
			if (startSize < 0) {
				randomFile.seek(0);
			} else {
				randomFile.seek(startSize);
			}
			String tmp = "";
			while ((tmp = randomFile.readLine()) != null) {
				logStr.append(tmp + "\r");
			}
		} finally {
			try {
				randomFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return logStr.toString();
	}

	public String getLogStrByRownum(String logfilePath, long rowNum) throws IOException {
		String root = ConfigConstants.LOG_ROOT;
		if (root.endsWith("/")) {
			root = root.substring(0, root.length() - 1);
		}
		File logFile = new File(root + File.separator + logfilePath);
		return FileContextUtil.readLastLines(logFile, rowNum);
	}
}
